package czk.concrent.threadpool.dymicthreadpool;

import lombok.SneakyThrows;

import java.util.concurrent.*;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/9/5 21:30
 */
public class DymicThreadPool {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                5,
                100L,
                TimeUnit.SECONDS,
                new MyLinkedBlockingQueue<>(3),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r);
                    }
                },
                // 设置拒绝策略
                new RejectedExecutionHandler() {
                    @SneakyThrows
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        MyLinkedBlockingQueue<Runnable> queue = (MyLinkedBlockingQueue)executor.getQueue();
                        System.out.println("放入拒绝队列里了");
                        queue.put(r);
                        System.out.println("被唤醒了");
                    }
                }
        );

        for (int i = 0; i < 10; i++) {
            threadPoolExecutor.submit(()->{
                System.out.println("开始了");
                try {
                    TimeUnit.MINUTES.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 重新设置容量
            MyLinkedBlockingQueue queue = (MyLinkedBlockingQueue) threadPoolExecutor.getQueue();
            queue.setCapacity(10);
        }

    }
}
